class UsersController < ApplicationController
  
   before_filter :login_required, :except=>[:new,:create]
   before_filter :admin_required, :only=>[:index]
   before_filter :ownership_required, :except=>[:index, :new, :create]

  # render new.rhtml
  def new
    @user = User.new
  end

  def index
      @users = User.find(:all)
  end

  def edit
      # now in ownership_required filter
      # @user = User.find(params[:id])
  end

  def update
      # now in ownership_required filter
      # @user = User.find(params[:id])
      
      # hack to keep non-admins from crafting a form to switch their
      # role
      user_params = params[:user]
      if user_params.key?("role") and not current_user.role == "administrator"
          user_params.delete("role")
      end


      
      if @user.update_attributes(user_params)
          flash[:notice] = "User updated successfully"
          redirect_to(@user)
      else
          flash[:notice] = "User update failed"
          render :action=>"edit"
      end
  end

  def show
      # now in ownership_required filter
      # @user = User.find(params[:id])
  end
 
  def create
    logout_keeping_session!
    @user = User.new(params[:user])
    success = @user && @user.save
    if success && @user.errors.empty?
            # Protects against session fixation attacks, causes request forgery
      # protection if visitor resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset session
      self.current_user = @user # !! now logged in
      redirect_back_or_default('/')
      flash[:notice] = "Thanks for signing up!  We're sending you an email with your activation code."
    else
      flash[:error]  = "We couldn't set up that account, sorry.  Please try again, or contact an admin (link is above)."
      render :action => 'new'
    end
  end
  private
    def ownership_required
        @user = User.find(params[:id])
        if current_user.role == "administrator"
            return true
            # should maybe change this to current_user!=@user
        elsif current_user.id != @user.id
            redirect_to(PermissionDeniedURL)
        else
            return true
        end
    end
end
